package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Register extends Activity {

	private EditText etEmail;
	private TextView lblResult;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.register);

		etEmail = (EditText)findViewById(R.id.register_content);
		lblResult = (TextView)findViewById(R.id.result);
	
		Button btnRegister = (Button) findViewById(R.id.register_button);
		btnRegister.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				
				String email = etEmail.getText().toString();
				
				Pattern p = Pattern.compile("[a-zA-Z0-9]@[a-zA-Z0-9]+.upenn.edu$");
				Matcher m = p.matcher(email);
				
				if (m.find()){		
					String password = generateString(new Random());
					String encrypted = encrypt(password);
					String result = register(email,password,encrypted);
					if(result.equals("Username already exists!")){
						lblResult.setText(result);
					}
					else{
						String s = "You will receive your temporary password in your inbox shortly. Please use it to log in for the first time!";

						lblResult.setText(result);
						
						//AlertDialog dialog = new AlertDialog.Builder(Register.this)
						if(result.equals("Email successfully delivered!")){
							new AlertDialog.Builder(Register.this)
							.setTitle(Register.this.getResources().getString(R.string.register_alert))  
							.setMessage(s)  
							//.setIcon(R.drawable.book)  
							.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									finish();
									Intent myIntent = new Intent(Register.this, LogIn.class);
									startActivityForResult(myIntent, 0);
								}
							})
							.show();
						}
					}
				}
				else{
					lblResult.setText("Not a valid email!");
				}			
			}
		});

	}
	
	public static final String REGISTER = "http://www.upennakpsi.org/lololol/pennmarketplace/register.php"; 

	private String register(String name, String password, String encrypted) {

		InputStream is = null;

		String returnString = "";

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("name",name));
		nameValuePairs.add(new BasicNameValuePair("password",password));
		nameValuePairs.add(new BasicNameValuePair("encrypted",encrypted));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(REGISTER);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			returnString = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			returnString=sb.toString();
		}catch(Exception e){
			//returnString += "\nError in converting...";
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		return returnString;
	}   
	
	public String encrypt(String password){
		String algorithm = "SHA";

		byte[] plainText = password.getBytes();

		MessageDigest md = null;

		try {		
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
		}

		md.reset();		
		md.update(plainText);
		byte[] encodedPassword = md.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				sb.append("0");
			}

			sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return sb.toString();
	}
	
	public static String generateString(Random rng)
	{
		String characters = "0123456789abcdefghijklmnopqrstuvwxyz";
	    char[] text = new char[4];
	    for (int i = 0; i < 4; i++)
	    {
	        text[i] = characters.charAt(rng.nextInt(characters.length()));
	    }
	    return new String(text);
	}


}
